package com.heima.behavior.service.impl;

import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApBehaviorEntryServiceImpl implements ApBehaviorEntryService {

    @Autowired
    MongoTemplate mongoTemplatel;
    @Override
    public ApBehaviorEntry findByUserIdOrEquipmentId(Integer userId, Integer equipmentId) {
        //1. 判断参数userid是否为空
        //不为空，使用userid查询， 为空就根据id创建实体类
        if (userId != null){
            Query query = Query.query(Criteria.where("refId").is(userId));
            ApBehaviorEntry entry = mongoTemplatel.findOne(query, ApBehaviorEntry.class);

            //如果entry为空说明没有创建实体类(就根据userid创建实体)
            if (entry == null){
                entry = new ApBehaviorEntry();
                entry.setRefId(userId);
                entry.setType((short) 1);
                entry.setCreatedTime(new Date());
                mongoTemplatel.save(entry);
            }
            return entry;
        }
        //如果设备id不等于空  就用设备的id查询，  数据不存在就通过设备id创建实体
        if (equipmentId != null){
            Query query = Query.query(Criteria.where("refid").is(equipmentId));
            ApBehaviorEntry entry = mongoTemplatel.findOne(query, ApBehaviorEntry.class);

            //为空就创建
            if (entry == null){
               entry =  new ApBehaviorEntry();
               entry.setRefId(equipmentId);
               entry.setType((short) 0);
               entry.setCreatedTime(new Date());
               mongoTemplatel.save(entry);
            }
            return entry;
        }
        //都没有就返回null;
        return null;
    }
}
